<script setup>
import { reactive, onMounted, watch, ref, computed } from "vue";
import {
  EyeOutlined,
  DeleteOutlined,
  VideoCameraOutlined,
  DownOutlined,
} from "@ant-design/icons-vue";
import request from "@/common/utils/request";
import NoticeFilm from "@/views/shotstack/MaterialCenter/modules/NoticeFilm.vue";
import store from "@/store/index.js";
// 视频预览组件
import viewVideo from "@/views/shotstack/components/dialogComponent/viewVideo.vue";
import utils from'@/common/utils/utils.js'

const viewVideoRef = ref(null);
// viewVideoRef.open(record.material_url)

import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
const router = useRouter();

const props = defineProps({
  // 发布至平台列表
  accountList: {
    type: Array,
    default: () => [],
  },
  editingRecordTitle: {
    type: String,
    default: ''
  }
});

const state = reactive({
   default_corver:  utils.staticPath + "images/workAi/shotstack/default_corver.png",

  visible: false,
  videoArr: [],
  queryData: {
    id: "",
    page: 1,
    pageSize: 10,
  },

  // 总数量
  total: 0,
  // 成功数量
  success_num: 0,
  // 失败数量
  fail_num: 0,
  // 轮询id
  timerId: "",

  // 全选
  checkAll: false,

  recordTitle: ''
});

const NoticeFilmRef = ref(null);


// 最后一页的数量信息
const lastPageData = computed(() => {
  // 最后一页
  const lastPage = Math.ceil(state.total / state.queryData.pageSize);
  // 最后一页的数量(如果正好 == 0 则返回 pageSize)
  const lastPageNum =
    state.total % state.queryData.pageSize || state.queryData.pageSize;
  console.log("最后一页的数量", lastPageNum);
  console.log("最后一页", lastPage);

  return {
    lastPage,
    lastPageNum,
  };
});

// 占位符数量
const placeholders = computed(() => {
  // 最后一页的数量
  if (state.queryData.page == lastPageData.value.lastPage) {
    console.log(
      "最后一页的数量阿撒旦法撒旦阿撒旦法撒旦",
      lastPageData.value.lastPageNum
    );
    return lastPageData.value.lastPageNum - state.videoArr.length;
  } else {
    console.log(
      "最后一页else",
      state.queryData.pageSize - state.videoArr.length
    );

    return state.queryData.pageSize - state.videoArr.length;
  }
});

const submitConfirm = () => {
  // alert('提交')
  controls.close();
};

let tid = "";
const getDetail = async () => {
  // 切换分页, 关闭全选
  state.checkAll = false;
  if (tid) {
    clearTimeout(tid);
    tid = "";
  }
  const res = await request.get(
    "/work_ai",
    "/user/shotstack/shotstackTask/detail",
    state.queryData
  );

  // xiaohongshu
  // 列表
  // res.result.list.data.forEach(i => i.relation.push({
  //   platform: 'xiaohongshu'
  // }))
  // res.result.list.data[0].relation.push({
  //   platform: 'xiaohongshu'
  // })
  // res.result.list.data[1].relation.push({
  //   platform: 'douyin'
  // })
  state.videoArr = res.result.list.data;
  // 失败数量
  state.fail_num = res.result.fail_num;
  // 成功数量
  state.success_num = res.result.success_num;
  // 总数
  state.total = res.result.total_num - state.fail_num;

  // 来源标题
  if(res.result?.editing_record?.title) {
    state.recordTitle = res.result?.editing_record?.title;
  }else{
    state.recordTitle = props.editingRecordTitle;
  }
  console.log(res, "详情雷彪");

  // 没有结束, 需要轮询
  if (placeholders.value != 0) {
    tid = setTimeout(() => {
      getDetail();
    }, 2500);
    console.log(tid, "timerIdtimerIdtimerIdtimerId");
  }
};

// 分页change事件
const PageChange = (page, pageSize) => {
  state.queryData.page = page; //当前页码
  state.queryData.pageSize = pageSize; //当前页数
  getDetail();
};

// 全部勾选的项
const selectItems = computed(() => {
  return state.videoArr.filter((ele) => ele?.checked) || [];
});

// 禁止发布的平台
const isDisabled = (key) => {
  // debugger
  // 没有勾选的项, 不禁用任何发布平台
  if (!selectItems.value.length) return false;
  console.log(
    selectItems.value,
    key,
    "selectItems.valueselectItems.valueselectItems.valueselectItems.value"
  );

  if(key == 'weixinshipinhao') return false

  return selectItems.value.some((ele) =>
    ele.relation.some((i) => i.platform == key)
  );
};

// 勾选视频
const selectItem = (item) => {
  item.checked = !item.checked;
  if (state.videoArr.every((ele) => ele.checked == item.checked)) {
    state.checkAll = item.checked;
  } else {
    state.checkAll = false;
  }
};

// 全选
const checkAllChange = () => {
  state.videoArr.forEach((ele) => {
    ele.checked = state.checkAll;
  });
};

const hasDyConfig = store?.state?.shotstack?.work_ai_config?.hasDyConfig || false;
// 发布视频
const handleMenuClick = (e) => {
  if (e?.developing == 1) {
    return message.warning("功能开发中");
  }
  // 如果被禁用, 禁止发布
  if (isDisabled(e.key)) return;
  if (e.key == "douyin" && hasDyConfig) {
    let choose = '2'
     NoticeFilmRef.value.showModal(e.key, choose);
  } else {
  let ids = selectItems.value.map((item) => item.multimedia_id);
  ids.length &&
    router.push({
      name: "AutoRelease",
      query: {
        platform: e.key,
        choose: "2",
        ids,
      },
    });
  }

};

const isSubmit = (e, type, ee_info) => {
  if (ee_info == '2') {
    let ids = selectItems.value.map((item) => item.multimedia_id);
     router.push({
        name: "AutoRelease",
        query: {
          platform: e,
          choose: "2",
          ids,
          type: type,
        },
      });
  } 
    
};

// 控制弹窗开关
const controls = {
  open: async (id) => {
    state.queryData.id = id;
    state.queryData.page = 1;
    getDetail();
    state.visible = true;
  },
  close: () => {
    state.visible = false;
  },
};

watch(
  () => state.visible,
  (nv, ov) => {
    if (!nv && tid) {
      clearTimeout(tid);
      tid = null;
    }
  }
);

defineExpose({
  controls,
});
</script>

<template>
  <a-drawer
    v-model:visible="state.visible"
    :destroyOnClose="true"
    class="custom-class"
    style="color: red"
    placement="right"
    :style="{
      'min-width': visible ? '1000px' : 0,
    }"
    :bodyStyle="{
      paddingTop: 0,
      color: '#42464e',
    }"
    :closable="false"
    :maskClosable="false"
    :keyboard="true"
    width="1000px"
  >
    <slot name="title">
      <div class="title_box">
        <h2>查看成片 <span style="font-size: 14px;margin-left: 2px;">(来源: {{ state.recordTitle }})</span> </h2>
      </div>
    </slot>
    <div class="content">
      <div class="title_controls">
        <a-checkbox v-model:checked="state.checkAll" @change="checkAllChange"
          >全选</a-checkbox
        >

        <div class="title_controls_right">
          <!-- <a-button type="">全部打包下载</a-button>
          <a-button type="">扫码发布</a-button> -->
          <a-dropdown placements="bottomRight" v-if="selectItems.length">
            <template #overlay>
              <a-menu style="margin-left: 20px">
                <a-menu-item
                  :key="account.key"
                  v-for="(account, index) in props.accountList"
                  :disabled="isDisabled(account.key)"
                >
                  <div
                    class="account_item"
                    @click="handleMenuClick(account, item, index)"
                  >
                    <img :src="account.image" alt="" /><span>{{
                      account.value
                    }}</span>
                  </div>
                </a-menu-item>
              </a-menu>
            </template>
            <a-button type="primary">
              发布至平台
              <DownOutlined />
            </a-button>
          </a-dropdown>
          <a-button type="primary" disabled v-else>
            发布至平台
            <DownOutlined />
          </a-button>
        </div>
      </div>

      <div class="center_list_box">
        <div
          @click="selectItem(item)"
          class="video_list_item"
          v-for="item in state.videoArr"
          :key="item.id"
        >
          <EyeOutlined
            class="toView"
            @click.stop="viewVideoRef.open(item.origin_url)"
          >
          </EyeOutlined>
          <a-checkbox
            class="checkbox"
            v-model:checked="item.checked"
          ></a-checkbox>
          <div class="material_box">

          
          <img v-if="item.poster && item?.poster !== '' " :src="item?.poster" alt="" 
            style="width: 100%; height: 100%; object-fit: contain;">

          <img v-else :src="state.default_corver" alt="" style="width: 100%; height: 100%;  object-fit: cover; 
              transform: scale(1.8); transform-origin: center;">

          </div>
          <div class="cart_msg">
            <span class="cart_type"
              >{{ item.material_type == "video" ? "视频" : "视频" }}
              <VideoCameraOutlined />
            </span>
            <span class="cart_time">{{ item.material_duration_text }}</span>
          </div>

          <div class="video_name">{{ item.multimedia_name || "" }}</div>
        </div>
        <!-- loding占位符 -->
        <!-- {{ placeholders + 'placeholders' }} -->
        <template v-if="placeholders >= 1">
          <div class="loding_item" v-for="item in placeholders" :key="item">
            <div class="loding_progress">
              <a-progress
                :percent="100"
                :showInfo="false"
                type="line"
                size="small"
                :stroke-color="{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }"
                status="active"
              />
            </div>
            <span class="loding_text">视频生成中, 请耐心等待...</span>
            <div class="loding_dec">
              <span>
                <LoadingOutlined></LoadingOutlined>
              </span>
              <span class="loding_dec_text">正在合成视频......</span>
            </div>
          </div>
        </template>
      </div>

      <!-- 分页器 -->
      <div class="pagination_box">
        <div class="page-total">共 {{ state.total }} 条</div>
        <a-pagination
          :total="state.total"
          :pageSize="state.queryData.pageSize"
          showSizeChanger="true"
          @change="PageChange"
        />
      </div>
    </div>
    <template #footer>
      <div class="bottom_btn">
        <a-button style="margin-right: 15px" @click="controls.close"
          >取消</a-button
        >
        <a-button type="primary" @click="submitConfirm" :loading="submitLoading"
          >确定</a-button
        >
      </div>
    </template>
  </a-drawer>

  <!-- 视频预览 -->
  <viewVideo ref="viewVideoRef"></viewVideo>

  <NoticeFilm ref="NoticeFilmRef" @handleOk="isSubmit"> </NoticeFilm>
</template>

<style scoped lang="less">
// 发布成片下拉样式
.account_item {
  width: 100px;
  height: 30px;
  display: flex;
  align-items: center;
  padding: 3px, 10px;

  img {
    margin-right: 5px;
    width: 20px;
    height: 20px;
  }
}

:deep(.ant-spin-container) {
  background-color: #131313;
  overflow: hidden;
}

.title_box {
  padding: 20px 0;

  h2 {
    margin: 0;
    font-weight: 600;
    font-size: 18px;
  }
}

// 整体样式
.content {
  width: 100%;
  height: calc(100% - 68px);
  // padding-top: 20px;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  // 头部全选等控制按钮
  .title_controls {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 0;

    .title_controls_right {
      display: flex;
      gap: 0 10px;
    }
  }

  // 中间列表
  .center_list_box {
    flex: 1;
    overflow-y: auto;
    width: 100%;
    display: grid;
    gap: 20px;
    grid-template-columns: repeat(auto-fit, minmax(170px, 170px));

    &::-webkit-scrollbar {
      width: 8px;
      height: 10px;
    }

    &::-webkit-scrollbar-thumb {
      background: #888;
      /* 滑块的背景颜色 */
      border-radius: 10px;
      /* 滑块的圆角 */
    }

    .video_list_item {
      height: 310px;
      width: 100%;
      background: #000;
      display: flex;
      // justify-content: center;
      flex-direction: column;
      align-items: center;
      position: relative;
      cursor: pointer;

      &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        z-index: 3;
        width: 100%;
        height: calc(100% - 30px);
        background: transparent;
        cursor: pointer;
        transition: all 0.3s;
      }

      &:hover {
        &::after {
          background: rgba(0, 0, 0, 0.5);
        }

        .toView {
          opacity: 1;
        }
      }

      .video_name {
        color: #000;
        font-weight: 600;
        background-color: #fff;
        width: 100%;
        line-height: 2;
        height: 30px;
        /* 溢出内容隐藏 */
        overflow: hidden;
        /* 文本溢出显示省略号 */
        text-overflow: ellipsis;
        /* 文本在一行显示 */
        white-space: nowrap;
      }

      .material_box {
        height: calc(100% - 30px);
        width: 100%;
        position: relative;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }

        video {
          width: 100%;
          height: 100%;
        }
      }

      // 预览小眼睛
      .toView {
        position: absolute;
        top: 40%;
        left: 50%;
        z-index: 9;
        opacity: 0;
        transition: all 0.3s;
        font-size: 25px;
        color: #fff;
        transform: translate(-50%);
        cursor: pointer;

        &:hover {
          color: var(--ss-primary-color-active);
        }
      }

      .checkbox {
        position: absolute;
        top: 3%;
        left: 10%;
        z-index: 9;
        transition: all 0.3s;
      }

      // 删除
      .cart_msg {
        display: flex;
        flex-direction: column;
        gap: 5px;
        position: absolute;
        bottom: 12%;
        left: 20%;
        z-index: 9;
        transition: all 0.3s;
        font-size: 13px;
        color: #fff;
        transform: translate(-50%);
        cursor: pointer;

        // &:hover {
        //   color: red;
        // }
      }
    }

    .loding_item {
      height: 310px;
      width: 100%;
      background-color: #e7e7e7;
      align-items: center;
      padding: 15px;
      position: relative;
      overflow: hidden;
      cursor: pointer;
      border-radius: 5px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: center;
      gap: 10px;

      .loding_progress {
        width: 100%;
      }

      .loding_text {
        font-weight: 600;
      }

      .loding_dec {
        .loding_dec_text {
          color: #9b9b9b;
          margin-left: 5px;
        }
      }
    }
  }

  // 分页器
  .pagination_box {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 20px;
  }
}

// 底部按钮
.bottom_btn {
  padding: 8px 24px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
}
</style>
